<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Session;
use Mail;
use Storage;
use App\org\SDK\REST;

class PersonalController extends Controller
{
    private $accountSid = null;
    private $accountToken = null;
    private $appId = null;
    private $serverIP = null;
    private $serverPort = null;
    private $softVersion = null;


    /**
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
     */
    //个人中心页面
    public function index()
    {
        $id = session('homeInfo')->id;
        $res = DB::table('users')->where('id','=',$id)->first();
        $data = DB::table('user_info')->where('id','=',$id)->first();
        return view('home.gerenziliao',['res'=>$res],['data'=>$data]);
    }


    //个人资料
    public function userinfo()
    {
        $id = session('homeInfo')->id;
        $res = DB::table('users')->where('id','=',$id)->first();
        $data = DB::table('user_info')->where('id','=',$id)->first();
        return view('home.gerenziliao',['res'=>$res],['data'=>$data]);

    }

    //个人安全页面
    public function gerenanquan()
    {

        $res = DB::table('users')->where('id','=',1)->first();
        return view('home.gerenanquan',['res'=>$res]);
    }

    //修改电话页面
    public function phone(Request $request)
    {
        $id = session('homeInfo')->id;
        $res = DB::table('users')->where('id', '=', $id)->first();
        return view('home.phone')->with('res', $res);
    }


    //修改手机  短信验证
    public function updatePhone(Request $request,$id = 1)
    {

                $this->accountSid= '8a216da85e0e48b2015e1421b3a90274';

        //主帐号Token
                $this->accountToken= '8217261312a04dddb6213d75d4dc4bba';

        //应用Id
                $this->appId='8a216da85e0e48b2015e1421b3f70278';

        //请求地址，格式如下，不需要写https://
                $this->serverIP='app.cloopen.com';

        //请求端口
                $this->serverPort='8883';

        //REST版本号
                $this->softVersion='2013-12-26';
        //Demo调用,参数填入正确后，放开注释可以调用
        $sj = rand(1000,9999);
        session(['yanzheng'=>$sj]);
        $this->sendTemplateSMS($request->input('yanzheng'),array($sj,'3'),1);

        $messages = [
            'required' => ':attribute 需要正确填写.',
            'size' => ':attribute 需要11位.',
            'yanzhengma' => ':attribute 验证码要4位.',


        ];
        $this->validate($request, [
            'phone1' => 'required|size:11',
            'yanzhengma' =>'required|max:4|min:4',
        ],$messages);
        $id = session('homeInfo')->id;
        DB::table('users')->where('id', '=', $id)->update(['phone' => $request->phone1]);
        return back();


    }

    //短信验证
    function sendTemplateSMS($to,$datas,$tempId)
    {
        // 初始化REST SDK
        $accountSid=$this->accountSid;
        $accountToken=$this->accountToken;
        $appId=$this->appId;
        $serverIP=$this->serverIP;
        $serverPort=$this->serverPort;
        $softVersion=$this->softVersion;
        $rest = new REST($serverIP,$serverPort,$softVersion);
        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);

        // 发送模板短信
        echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        if($result == NULL ) {
            echo "result error!";

        }
        if($result->statusCode!=0) {
            echo "error code :" . $result->statusCode . "<br>";
            echo "error msg :" . $result->statusMsg . "<br>";
            //TODO 添加错误处理逻辑
        }else{
            echo "Sendind TemplateSMS success!<br/>";
            // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            echo "dateCreated:".$smsmessage->dateCreated."<br/>";
            echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
            //TODO 添加成功处理逻辑
        }
    }


    //修改密码页面
    public function mima()
    {
        return view('home.mima');
    }


    //修改密码
    public function updateMima(Request $request, $id)
    {
        $id = session('homeInfo')->id;
        $pwd = $request->password;
        $pwd1 = $request->password1;
        if($pwd == $pwd1){
            $res = DB::table('users')->where('id', '=', $id)->update(['password' => $request->password]);
            return redirect('/gerenanquan');
        }else{

            return back();
        }


    }


    //修改邮箱页面
    public function mail()
    {
        return view('home.mail');
    }


    //修改邮箱
    public function updateMail(Request $request, $id = 1)
    {
        $res = DB::table('users')->where('id', '=', $id)->update(['email' => $request->email]);
        return redirect('/gerenanquan');
    }


    //修改用户名页面
    public function username()
    {
        return view('home.username');
    }


    //修改用户名
    public function updateName(Request $request)
    {
        $id = session('homeInfo')->id;
        DB::table('users')->where('id', $id)->update(['name' => $request->name]);
        return redirect('userinfo');
    }


    //地址页面
    public function dizhi(Request $request)
    {
        $id = session('homeInfo')->id;
        $res = DB::table('user_info')->where('uid','=',$id)->get();
        return view('home.dizhi',['res'=>$res]);
    }

    //新增地址页面
    public function address()
    {
        return view('home.address');
    }


    //删除地址
    public function deleteAdress(Request $request,$id)
    {

        DB::table('user_info')->where('id',$id)->delete();
        return back();
    }

    //新增地址
    public function addAddress(Request $request)
    {
        $id = session('homeInfo')->id;
        $ary = ['name' => $request->name,'uid'=>$id,'sex' => $request->sex,'address'=>$request->address,'tel'=>$request->tel];
        DB::table('user_info')->insert($ary);
        return redirect('/dizhi');
    }

    //订单
    public function dingdan()
    {
        //$id = session('homeInfo')->id;
        //$res = DB::table('indent')->where('uid','=',$id)->get();
        $res = DB::table('indent')
            ->join('merchant', 'indent.mid', '=', 'merchant.id')
            ->join('goods', 'merchant.id', '=', 'goods.mid')
            ->select('indent.*', 'merchant.name', 'goods.name','indent.money','indent.status','merchant.photo','merchant.id','indent.id')
            ->get();

        return view('home.dingdan',['res'=>$res]);
    }

    public function pingjia($id,$mid)
    {

        $res = $id;

        $data = $mid;

        return view('home.pingjia')->with('res', $res)->with('data',$data);



    }
    public function addPingjia(Request $request)
    {

        $id = session('homeInfo')->id;
        $data = date("Y-m-d",time());

        $ary = ['mid' => $request->id,'uid'=>$id,'comment' => $request->neirong,'dafen'=>$request->dafen,'goods'=>$request->mid,'time'=>$data];

        DB::table('yonghupinglun')->insert($ary);
        return back();
    }

    //邮箱发送
    public function send()
    {
        $name = '第一封邮件';
        $flag = Mail::send('home.email_test', ['name' => $name], function ($message) {
            $to = '545080045@qq.com';
            $message->to($to)->subject('测试邮件');
        });
        if ($flag) {
            echo '发送邮件成功，请查收！';
        } else {
            echo '发送邮件失败，请重试！';
        }
    }

    public function test()
    {

        dd($this->id);
    }

    public function photo()
    {
        $id = session('homeInfo')->id;
        $res = DB::table('user_info')->where('uid',$id)->first();
        return view('home.photo',['res'=>$res]);
    }

    public function photofrom(Request $request)
    {
        $id = session('homeInfo')->id;
        $img = $request->file('img');
        if($img->isValid()){
            //$picname = $file->getClientOriginalName(); //获取上传原文件名
            $ext = $img->getClientOriginalExtension(); //获取上传文件名的后缀名
            //执行移动上传文件
            $path = public_path('upload/images/');
            $name = "origin_".time().rand(1,9999).".".$ext;
            if($img->move($path,$name)){
                $url = '/upload/images/'.$name;
                DB::table('user_info')->insert(
                    ['uid' => $id]);
                DB::table('user_info')->where('uid',$id)->update(["photo"=>$url]);
                return redirect('photo');
            }else{
                return redirect('photo');
            }

        }

    }


}